/*
 * �ļ���XmlDAO.java
 * ��������������
 * �޸��ˣ�֣ΰΰ
 * �޸�ʱ�䣺����4:49:39
 * �޸����ݣ����޸����ݡ�
 * �汾�ţ�1.0
 */

package cputils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlUtils {
	private static String fileName = "data.xml";
	private static String filePath = "config/";

	public static void main(String[] args) {
		XmlUtils dao = new XmlUtils();
		List<DataItem> list;
		try {
			//list = dao.list("ssq");
//			for (DataItem dataItem : list) {
//				//System.out.println(dataItem.getId()+":"+dataItem.getOpencode());
//			}
			//dao.tjSSQ();
			//dao.importDLTData(8001, 8002);
			/*for (int i = 0; i < 1000; i++) {
				dao.deleteItem(i+"");
			}*/
			dao.importDLTData(14001, 14100);
			//dao.importSSQData(2003001, 2014109);
//			System.out.println(dao.tjDLT(true));
			System.out.println(dao.tjSSQ(true));
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public Map<String, Map<Integer, Integer>> tjSSQ(boolean isSorted) throws DocumentException, IOException{
		Map<String, Map<Integer, Integer>> res = new HashMap<String, Map<Integer,Integer>>();
		List<DataItem> list = list("ssq");
		Map<Integer, Integer> bMap = new HashMap<Integer, Integer>();
		Map<Integer, Integer> aMap = new HashMap<Integer, Integer>();
		for (int i = 1; i <= 33; i++) {
			bMap.put(i, 0);
		}
		for (int i = 1; i <= 16; i++) {
			aMap.put(i, 0);
		}
		for (DataItem dataItem : list) {
			String[] codeArr = dataItem.getOpencode().split(" ");
			for (int i=0,size=codeArr.length; i<size ; i++) {
				int num = Integer.parseInt(codeArr[i]);
				if (i<6) {
					bMap.put(num, bMap.get(num)+1);
				}else {
					aMap.put(num, aMap.get(num)+1);
				}
			}
		}
		res.put("b", bMap);
		res.put("a", aMap);
//		System.out.println(res);
		return makeMap(res, isSorted);
	}
	
	
	public Map<String, Map<Integer, Integer>> tjDLT(boolean isSorted) throws DocumentException, IOException{
		Map<String, Map<Integer, Integer>> res = new HashMap<String, Map<Integer, Integer>>();
		List<DataItem> list = list("dlt");
		Map<Integer, Integer> bMap = new LinkedHashMap<Integer, Integer>();
		Map<Integer, Integer> aMap = new LinkedHashMap<Integer, Integer>();
		for (int i = 1; i <= 35; i++) {
			bMap.put(i, 0);
		}
		for (int i = 1; i <= 12; i++) {
			aMap.put(i, 0);
		}
		for (DataItem dataItem : list) {
			String[] codeArr = dataItem.getOpencode().split(" ");
			for (int i=0,size=codeArr.length; i<size ; i++) {
				int num = Integer.parseInt(codeArr[i]);
				if (i<5) {
					bMap.put(num, bMap.get(num)+1);
				}else {
					aMap.put(num, aMap.get(num)+1);
				}
			}
		}
		res.put("b", bMap);
		res.put("a", aMap);
		//System.out.println(res);
		return makeMap(res, isSorted);
	}
	
	public static Map<String, Map<Integer, Integer>> makeMap(Map<String, Map<Integer, Integer>> res,boolean isSorted){
		if (isSorted) {
			Map<Integer, Integer> bMap = res.get("b");
			Map<Integer, Integer> aMap = res.get("a");
			List<KeyValueItem> bItems = new ArrayList<KeyValueItem>();
			List<KeyValueItem> aItems = new ArrayList<KeyValueItem>();
			for (Entry<Integer, Integer> entry : bMap.entrySet()) {
				KeyValueItem item = new KeyValueItem(entry.getKey(),entry.getValue());
				bItems.add(item);
			}
			for (Entry<Integer, Integer> entry : aMap.entrySet()) {
				KeyValueItem item = new KeyValueItem(entry.getKey(),entry.getValue());
				aItems.add(item);
			}
			aItems = sortList(aItems);
			bItems = sortList(bItems);
			bMap = new LinkedHashMap<Integer, Integer>();
			aMap = new LinkedHashMap<Integer, Integer>();
			for (KeyValueItem item : aItems) {
				aMap.put(item.key, item.value);
			}
			for (KeyValueItem item : bItems) {
				bMap.put(item.key, item.value);
			}
			res.put("b", bMap);
			res.put("a", aMap);
		}
		return res;
	}
	private static List<KeyValueItem> sortList(List<KeyValueItem> list){
		Collections.sort(list, new Comparator<KeyValueItem>(){
			public int compare(KeyValueItem o1, KeyValueItem o2) {
				return o2.value - o1.value;
			}
		});
		return list;
	}
	
	
	
	
	
	
	
	
	
	
	
	public void importSSQData(Integer begin,Integer end) throws IOException, DocumentException{
		begin = begin == 0?2014001:begin;
		if (begin>=end) {
			throw new DocumentException("end must big than begin.");
		}
		Map<String, String> ssqMap = null;
		for (int i = begin; i <= end; i++) {
			if (Integer.parseInt((i+"").substring((i+"").length()-3))>160) {
				continue;
			}
			ssqMap = CPDataService.getSSQData(i+"");
			if (ssqMap!=null) {
				DataItem item = new DataItem();
				item = new DataItem(i+"",ssqMap.get(i+""),"ssq");
				addItem(item);
			}
		}
	}
	
	public void importDLTData(Integer begin,Integer end) throws DocumentException, IOException{
		begin = begin == 0?14001:begin;
		if (begin>=end) {
			throw new DocumentException("end must big than begin.");
		}
		Map<String, String> dltMap = null;
		for (int i = begin; i <= end; i++) {
			
			if (Integer.parseInt((i+"").substring((i+"").length()-3))>180) {
				continue;
			}
			dltMap = CPDataService.getDLTData((i+"").length()==5?(i+""):"0"+i+"");
			if (dltMap!=null) {
				DataItem item = new DataItem();
				item = new DataItem(i+"",dltMap.get(i+""),"dlt");
				addItem(item);
			}
		}
	}
	//���ֱ�ո�
	public static String replaceHanzi(String sourceStr,String replaceStr){
		String regEx="[\u4E00-\u9FA5]"; //han zi
		Pattern pat=Pattern.compile(regEx);  
		Matcher mat=pat.matcher(sourceStr);  
		String res = mat.replaceAll(replaceStr);
		//System.out.println(res);
		return res;
	}

	public Document getDocument(String type) throws DocumentException, IOException {
		SAXReader reader = new SAXReader();
		reader.setEncoding("UTF-8");
		File file = new File(filePath+type+fileName);
		if(!file.exists()){
			throw new FileNotFoundException("FileNotFound:"+type+fileName);
		}
		Document document = reader.read(file);
		return document;
	}

	public List<DataItem> list(String type) throws DocumentException, IOException {
		List<DataItem> list = new ArrayList<DataItem>();
		Document root = getDocument(type);
		Element rootEl = root.getRootElement();
		Iterator<Element> it = rootEl.elementIterator();
		Element el;
		DataItem item;
		while (it.hasNext()) {
			el = it.next();
			item = new DataItem(el.attributeValue("ID"),el.attributeValue("opencode"),el.attributeValue("type"));
			list.add(item);
		}
		return list;
	}

	
	
	public int addItem(DataItem item) throws DocumentException, IOException {
		Document root = getDocument(item.getType());
		Element rootEl = root.getRootElement();
		if (rootEl.elementByID(item.getId())!=null) {
			System.err.println(item.getType()+" number:"+item.getId()+" is existed.");
			writeLogs(item.getType()+" number:"+item.getId()+" is existed.", this.getClass(), null);
			return 0;
		}
		List<Element> list = rootEl.elements();
		Element el = DocumentHelper.createElement("item");
		el.addAttribute("ID", item.getId());
		el.addAttribute("opencode",item.getOpencode());
		el.addAttribute("type",item.getType());
		list.add(el);
		writeDoc(root,item.getType());
		return 1;
	}
	public int deleteItem(String id,String type) throws DocumentException, IOException{
		Document root = getDocument(type);
		Element rootEl = root.getRootElement();
		//rootEl.elementByID("10001");
		Element deleteEl = rootEl.elementByID(id);
		//Node deleteEl = rootEl.selectSingleNode("//item/");
		boolean flag = rootEl.remove(deleteEl);
		if(flag){
			writeLogs(type+" delete number:"+id, this.getClass(), null);
		}else {
			writeLogs(type+" delete number:"+id+" error.", this.getClass(), null);
		}
		writeDoc(root,type);
		return 1;
	}

	public int writeDoc(Document document,String type) throws IOException {
		OutputFormat former =OutputFormat.createPrettyPrint();//���ø�ʽ�������  
        former.setEncoding("UTF-8");  
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(filePath+type+fileName),"UTF-8"),former);  
		writer.write(document);
		writer.close();
		return 1;
	}
	
	public static void writeLogs(String message,Class<?> clazz,Exception e1){
        try {
            File logFile = new File(filePath+"log.log");
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            FileOutputStream fileOutputStream = new FileOutputStream(logFile,true);
            OutputStreamWriter  writer = new OutputStreamWriter (fileOutputStream);
            StringBuffer buffer = new StringBuffer();
            buffer.append(format.format(new Date())).append("] [").append(clazz.getName()).append("] [").append(message).append("]\r\n");
            writer.write(buffer.toString());
            if (e1!=null) {
            	PrintWriter log = new PrintWriter(writer, true);
                e1.printStackTrace(log);
			}
            writer.close();
            fileOutputStream.close();
        } catch (IOException e) {
            System.err.println("file write fail:" + e.getMessage());
        }
    }
	
	public static List<String> getHMData(String issueNo) throws IOException{
		List<String> list = new ArrayList<String>();
		File file = new File(filePath+issueNo+".txt");
		if (!file.exists()) {
        	throw new FileNotFoundException("file not found...");
        }
		FileReader fileReader = new FileReader(file);
		BufferedReader reader = new BufferedReader(fileReader);
		String con;
		while((con = reader.readLine())!=null){
			list.add(con);
		}
		return list;
	}
	
	public static void writeFile(String message,String fileName,boolean append){
		try {
            File file = new File(filePath+fileName);
            if (!file.exists()) {
            	file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file,append);
            OutputStreamWriter  writer = new OutputStreamWriter (fileOutputStream);
            writer.write(message);
            writer.close();
            fileOutputStream.close();
        } catch (IOException e) {
            System.err.println("file write fail:" + e.getMessage());
        }
	}
}

class KeyValueItem{
	public Integer key;
	public Integer value;
	public KeyValueItem(Integer key,Integer value){
		this.key = key;
		this.value = value;
	}
}
